package com.ljkj.cordial.chat.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lanjiu.lib.app.App;
import com.lanjiu.lib.business.FileTransmissionManager;
import com.lanjiu.lib.business.OriginalPictureVideoTransmissionCreator;
import com.lanjiu.lib.business.listener.FileTransmissionListener;
import com.lanjiu.lib.imclient.dto.VersionDto;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.file.FileOperator;
import com.lanjiu.lib.utils.log.Logger;
import com.ljkj.cordial.chat.BuildConfig;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.BaseActivity;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.VersionInfoView;
import com.nic.view.util.JToast;
import com.yanzhenjie.album.util.AlbumUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 版本信息
 */
public class VersionInfoActivity extends AppEventActivity<VersionInfoView> {

    public static boolean IS_RUNNING = false;

    @BindView(R.id.tv_current_version)
    TextView tvCurrentVersion;
    @BindView(R.id.tv_nearby_version)
    TextView tvNearbyVersion;
    @BindView(R.id.tv_update_version)
    TextView tvUpdateVersion;
    @BindView(R.id.progress_update)
    ProgressBar progressUpdate;
    @BindView(R.id.panel_desc)
    LinearLayout panelDesc;
    @BindView(R.id.tv_new_version_desc)
    TextView tvNewVersionDesc;
    private String mPath;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_version_info;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        getToolbar().setTitle("版本信息");
        tvCurrentVersion.setText(BuildConfig.VERSION_NAME);

//        File folder = AlbumUtils.getAlbumExtraFile(App.getContext(), AlbumUtils.PACK_NAME, UserPreferences.getUserId());
//        FileOperator.mkDirectory(folder);

    }

    @Override
    protected void onStart() {
        super.onStart();
        IS_RUNNING = true;
    }

    @Override
    protected void onStop() {
        IS_RUNNING = false;
        super.onStop();
    }

    @Override
    protected boolean afterOnStartRegisterEventBus() {
        obtainView().doCheckUpdate();
        return super.afterOnStartRegisterEventBus();
    }

    public static void installApk(Context context, String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(path);
        Logger.print("安装路径==" + path);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".apk.provider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public static String getTargetPath(String serverPath) {
        File folder = AlbumUtils.getAlbumExtraFile(App.getContext(), AlbumUtils.PACK_NAME, UserPreferences.getUserId());
        FileOperator.mkDirectory(folder);
        String targetPath = folder.getAbsolutePath()+ File.separator + FileOperator.getFileName(serverPath, true);
        File file = new File(targetPath);
        if (file.exists()) file.delete();
        return targetPath;
    }

    @Override
    protected VersionInfoView bindNettyMessageView() {
        return new VersionInfoView((code, msg, data) -> {
            if (code == IMSContacts.ResponseCode.SUCCESS && data != null && BuildConfig.VERSION_CODE < data.getVersionCode()) {
                tvNearbyVersion.setText(data.getVersionName());
                panelDesc.setVisibility(View.VISIBLE);
                tvNewVersionDesc.setText(data.getUpdateDescribe());

                final String serverPath = data.getUpdatePath();
                final String targetPath = getTargetPath(serverPath);
                tvUpdateVersion.setOnClickListener(v -> {
                    if(TextUtils.isEmpty(mPath)) {
                        FileTransmissionManager.getInstance().buildDownloader()
                                .targetPath(targetPath)
                                .serverPath(serverPath)
                                .friend(OriginalPictureVideoTransmissionCreator.apk(UserPreferences.getUserId()))
                                .onFileReceiver(new FileTransmissionListener.OnFileReceiverListener() {
                                    @Override
                                    public void onStart() {
                                        progressUpdate.setProgress(0);
                                    }

                                    @Override
                                    public void onProgress(int progress) {
                                        progressUpdate.setProgress(progress);
                                    }

                                    @Override
                                    public void onComplete(String path) {
                                        mPath = path;
                                        installApk(VersionInfoActivity.this, path);
                                    }

                                    @Override
                                    public void onError(int code, String msg) {
                                        progressUpdate.setProgress(100);
                                        JToast.showShort(VersionInfoActivity.this, "下载失败！");
                                    }
                                })
                                .download();
                    } else {
                        installApk(VersionInfoActivity.this, mPath);
                    }
                });
            } else {
                tvNearbyVersion.setText(tvCurrentVersion.getText());
                tvUpdateVersion.setOnClickListener(v -> JToast.showShort(VersionInfoActivity.this, "当前已是最新版本"));
            }
        });
    }
}
